package com.hf.wujian.netty;

import com.google.gson.Gson;
import com.hf.wujian.dispatch.BSHDispatch;
import com.hf.wujian.model.GameHall;
import com.hf.wujian.model.GameUser;
import com.hf.wujian.model.imp.BSHGameHall;
import com.hf.wujian.model.imp.BSHGameUser;
import com.hf.wujian.utils.MapUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * 调度逻辑处理类
 *
 * @author hf
 * @date 2018/11/23
 * @version 1.0
 */
public class BSHServerHandler extends SimpleChannelInboundHandler<String> {

    private BSHGameHall gameHall;
    private Map<Integer,Class> dispatchs;

    /**
     * @param gameHall 游戏大厅
     * @param dispatchs 调度类
     */
    public BSHServerHandler(BSHGameHall gameHall,Map<Integer,Class> dispatchs){
        this.gameHall = gameHall;
        this.dispatchs = dispatchs;
    }

    /**
     * 调度方法
     *
     * @param ctx 客户端通道
     * @param s 客户端消息
     * @throws Exception
     */
    protected void channelRead0(ChannelHandlerContext ctx, String s) throws Exception {

        // 收到消息直接打印输出
        System.out.println(ctx.channel().remoteAddress() + " Say : " + s);
        NettyMsg nettyMsg = new Gson().fromJson(s,NettyMsg.class);

        Class mclass = dispatchs.get(nettyMsg.getCommand());
        //如果调度器不存在就直接退出
        if(mclass == null){
            return;
        }

        //如果调度器未实现调度接口直接退出
        Object object = mclass.newInstance();
        if(!(object instanceof BSHDispatch)){
            return;
        }

        String userName = (String) MapUtils.getValue(nettyMsg.getData(),"userName");
        //创建用户
        GameUser gameUser = gameHall.getGameUser(nettyMsg.getUuid());
        if(gameUser == null){
            gameUser = new BSHGameUser(userName,nettyMsg.getUuid(),ctx,gameHall);
        }

        //执行调度
        Method method = mclass.getMethod("dispatch",ChannelHandlerContext.class,NettyMsg.class,GameHall.class,GameUser.class);
        method.invoke(object,ctx,nettyMsg,gameHall,gameUser);

        System.out.println("用户人数：" + gameHall.getGameUserSize());
        System.out.println("房间数量：" + gameHall.getGameRoomSize());
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //System.out.println("Server active ");
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        //System.out.println("Server close ");
        super.channelInactive(ctx);
    }
}
